﻿var http = require('http')
	, fs = require('fs');

var pipeFile = function(path, res) {
	res.writeHead('200');
	fs.createReadStream(path).pipe(res);
}
var getCurrTime = function(){
    var d  = new Date();
    return d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate()+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
}
var server = http.createServer(function(req, res) {
	if (req.url.length == 1)
		req.url = "/index.html";
	req.url = "." + req.url;
	fs.exists(req.url, function(exists) {
		if (!exists) {
			console.log("cant find the following url", req.url);
			res.writeHead(404);
			res.end();
			return;
		}
		res.writeHead(200);
		var file = fs.createReadStream(req.url);
		file.pipe(res);
	});
}).listen(8080);
var io = require('socket.io').listen(server);

var lockCanvas = 0;
var gameId = 0;
var userId;

io.sockets.on('connection', function(sock) {
	sock.on('msg', function(msg){
		var data = {username: sock.name, time: getCurrTime(), msg: msg};
		sock.emit('msg', data);
		sock.broadcast.emit('msg', data);
	});
	sock.on('data', function(data) {
		sock.emit('data', data);
		sock.broadcast.emit('data', data);
	});
	sock.on('login', function(username){
		sock.name = username;
		var data = {username: sock.name, time: getCurrTime(), msg: '上线咯。。。'};
		sock.broadcast.emit('sysMsg', data);
		sock.emit('sysRes', {type: "userId", userId: gameId});
		gameId = gameId + 1;
	});
	sock.on('logout', function(msg){
		var data = {username: sock.name, time: getCurrTime(), msg: '下线咯。。。'};
		sock.broadcast.emit('sysMsg', data);
		if(msg.userId == userId) {
			lockCanvas = 0;
		}
	});
	sock.on('syscall', function(msg){
		if(msg.type == "applyCanvas") {
			if(lockCanvas == 0) {
				lockCanvas = 1;
				sock.broadcast.emit('sysRes', {type: "lockCanvas"});
				sock.emit('sysRes', {type: "unlockCanvas"});
				userId = msg.userId;
			}
		}
	});
});
console.log("You can start the game by going to 127.0.0.1:8080, if you want to join the game with another pc go to <pc name or ip of server pc>:8080");
